package com.rpc.center.manager;

import com.google.common.collect.Lists;
import com.rpc.center.entity.PublisherNode;
import com.rpc.common.entity.HostInfoPair;
import io.netty.channel.Channel;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class RPCServiceStore {

    //todo 目前服务的信息直接放内存，后续可能需要改动，不然服务量巨大时内存会不足
    private Map<String, List<PublisherNode>> serviceInfoCenter = new ConcurrentHashMap<>();

    /**
     * 注册服务
     */
    public synchronized void registService(String serviceID, PublisherNode publisherNode) {
        List<PublisherNode> serverList = serviceInfoCenter.getOrDefault(serviceID, null);
        if (serverList == null) {
            serverList = Lists.newArrayList();
        }
        serverList.add(publisherNode);
        serviceInfoCenter.put(serviceID, serverList);
    }

    /**
     * 查找服务
     *
     * @param serviceID
     * @return
     */
    public List<PublisherNode> searchService(String serviceID) {
        return serviceInfoCenter.getOrDefault(serviceID, null);
    }


    public synchronized PublisherNode getPublisherByChannel(Channel channel){
        for(Map.Entry<String,List<PublisherNode>> entry:serviceInfoCenter.entrySet()){
            List<PublisherNode> publisherNodeList=entry.getValue();
            for(PublisherNode publisherNode:publisherNodeList){
                if(publisherNode.getChannel()==channel){
                    return publisherNode;
                }
            }
        }
        return null;
    }
}
